package com.it.chinamobileai.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.it.chinamobileai.domain.Conversation;
import com.it.chinamobileai.mapper.ConversationMapper;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class MysqlChatMemory implements ChatMemory {
    @Autowired
    private ConversationMapper conversationMapper;
    @Override
    public void add(String conversationId, List<Message> messages) {
        List<Conversation> list = messages.stream().map(message -> {
            return Conversation.builder()
                    .type(message.getMessageType().getValue())
                    .message(message.getText())
                    .conversationId(conversationId)
                    .createTime(LocalDateTime.now())
                    .build();
        }).toList();
        conversationMapper.insert(list);
    }

    @Override
    public List<Message> get(String conversationId) {
        //sql：select * from conversation where conversation_id = ?
        List<Conversation> conversations = conversationMapper.selectList(new LambdaQueryWrapper<Conversation>()
                .eq(Conversation::getConversationId, conversationId));
        return conversations.stream().map(c->{
            Message message = null;
            if (MessageType.USER.getValue().equals(c.getType())) {
                //用户说的话
                message =  new UserMessage(c.getMessage());
            }else if (MessageType.ASSISTANT.getValue().equals(c.getType())) {
                //用户说的话
                message = new AssistantMessage(c.getMessage());
            }
            return message;
        }).toList();
    }

    @Override
    public void clear(String conversationId) {
//sql：delete from conversation where conversation_id = ?
        conversationMapper.delete(new LambdaQueryWrapper<Conversation>().eq(Conversation::getConversationId,conversationId));
    }
}
